﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MakeItWeb.Framework;

namespace AllNations.UI
{
    public partial class VideoIntegration : MakeItWebPage, IDynamicPage
    {
        Framework.VideoIntegrationConfiguration _Config = new Framework.VideoIntegrationConfiguration();

        private string YouTubeKeyword
        {
            get { return _Config.YouTubeKeyword; }
        }

        protected override void OnPreInit(EventArgs e)
        {
            base.OnPreInit(e);
            _Config.Deserialize(CurrentHtmlPage.PageSettings);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (string.IsNullOrEmpty(_Config.YouTubeAuthorName))
                    return;

                var videos = YouTubeHelper.ListVideoByAuthor(_Config.YouTubeAuthorName);

                var cs = from v in videos
                         where string.IsNullOrEmpty(YouTubeKeyword) || v.Keywords.Contains(YouTubeKeyword)
                         select new { v.VideoId, v.Title, ThumbnailUrl = v.Thumbnails.FirstOrDefault().Url, v.Updated, VideoUrl = GetVideoUrl(v) };

                var selVideo = cs.FirstOrDefault();
                if (string.IsNullOrEmpty(Request.QueryString["VideoId"]) == false)
                    selVideo = cs.Where(v => v.VideoId == Request.QueryString["VideoId"]).FirstOrDefault();
                
                rptVideo.DataSource = cs.Where(v => v.VideoId != selVideo.VideoId).OrderByDescending(v => v.Updated);
                rptVideo.DataBind();

                if (selVideo != null)
                {
                    Literal litYouTubeVideo = new Literal();
                    litYouTubeVideo.Text = string.Format(@"<iframe width=""658"" height=""493"" src=""http://www.youtube.com/embed/{0}"" frameborder=""0"" allowfullscreen></iframe>", selVideo.VideoId);
                    pldYouTubeVideo.Controls.Add(litYouTubeVideo);
                }
            }
        }

        private string GetVideoUrl(Google.YouTube.Video v)
        {
            return string.Format("{0}?VideoId={1}", Request.Path, v.VideoId);
        }

        string IDynamicPage.GetPageConfigurationControl()
        {
            return "~/UI/Controls/VideoIntegrationConfiguration.ascx";
        }

        string IDynamicPage.PageTypeName
        {
            get { return "YouTube"; }
        }
    }
}